package org.im.service.user.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.im.service.user.bean.UserInfo;
import org.im.service.user.ift.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//@Service("jssdbUserService")
public class JssdbUserService extends JssdbService implements UserService {

    @Override
    public UserInfo register(String userName, String password, String nickName) {
        if(isUserExist(userName)) {
            log.debug("user exist [{}]", userName);
            return null;
        }
        UserInfo userInfo = new UserInfo();
        
        userInfo.setPasswordMd5(password);
        userInfo.setRegisterDate(new Date());
        userInfo.setSessionId(null);
        userInfo.setUserId(createUserId());
        userInfo.setUserName(userName);
        userInfo.setUserNick(nickName);
        
        setUserInfoByUserName(userName, userInfo);
        
        return userInfo;
    }

    @Override
    public UserInfo login(String userName, String password) {
        if(isUserExist(userName)) {
            log.debug("user exist [{}]", userName);
            return null;
        }
        
        UserInfo userInfo = getUserInfo(userName);
        if(userInfo != null && userInfo.getPasswordMd5().equals(password)) {
            userInfo.setPasswordMd5(null);
            return userInfo;
        }
        return null;
    }

    @Override
    public boolean isLogin(String userName) {
        String sessionId = getSessionId(userName);
        return StringUtils.isNotBlank(sessionId);
    }

    @Override
    public UserInfo getUserInfo(String userName) {
        
        return getUserInfoByUserName(userName);
    }
    
    @Override
    public boolean isUserExist(String userName) {
        return getUserInfo(userName) != null;
    }

    private static final long BASE_ID = (long) Math.pow(10, 32);
    
    private String createUserId() {
        long increaseId = jssdbClient.increase("USER_ID_", 1);
        return String.valueOf(BASE_ID + increaseId);
    }
    
    private static Logger log = LoggerFactory.getLogger(JssdbUserService.class);
}
